<template>
  <el-tabs v-model="tabActive" class="demo-tabs" @tab-click="tabClick">
    <el-tab-pane
      v-for="item in tabList" 
      :key="item.id" 
      :label="item.name" 
      :name="item.id"
      :disabled="item.id === 2 && pageStatus === 1"
    >
      <div v-if="item.id === 1">
        <ContentWrap>
          <div class="content">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">事故信息</div>
            </div>
            <div class="content_main">
              <el-form 
                ref="formRef" 
                :inline="true" 
                :model="formData.data" 
                :rules="formRules" 
                class="-mb-15px"
                label-width="auto"
              >
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="预估事故等级" prop="levelId">
                      <el-select v-model="formData.data.levelId" filterable clearable placeholder="请选择事故等级">
                        <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="责任部门" prop="departmentId">
                      <el-tree-select
                        class="formInp"
                        v-model="formData.data.departmentId"
                        :data="deptTree"
                        filterable
                        clearable
                        :props="defaultProps"
                        check-strictly
                        default-expand-all
                        placeholder="请选择责任部门"
                        value-key="deptId"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="事故时间" prop="accidentTime">
                      <el-date-picker
                        v-model="formData.data.accidentTime"
                        style="width: 100%"
                        type="date"
                        placeholder="请选择编制时间"
                        @change="e => formData.data.accidentTime = formatDateToYMD(e)"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申报人" prop="declarePersonId">
                      <div class="flex-s" style="width: 100%">
                        <div class="coord flex-s formInp mr-12">
                          <span v-if="formData.data.declarePersonName">{{ formData.data.declarePersonName }}&nbsp;({{ formData.data.declarePersonPhone }})</span>
                          <span v-else style="color: rgb(159 155 155);">请选择申报人</span>
                        </div>
                        <el-button type="primary" @click="addCompanies(1, '申报人')">选择申报人</el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="事故地点" prop="address">
                      <el-input class="formInp" v-model="formData.data.address" clearable placeholder="请输入事故地点"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="事故简述" prop="remark">
                      <el-input
                        v-model="formData.data.remark"
                        type="textarea"
                        maxlength="200"
                        :autosize="{ minRows: 6}"
                        placeholder="请输入事故简述信息"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="事故附件" prop="attachment">
                      <div class="upload_box" style="width: 100%;">
                        <UploadFile
                          v-model="formData.data.attachment"
                          class="upload-demo"
                          :fileSize="20"
                          :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
                          :limit="10"
                        />
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="事故照片" prop="accidentPhotos">
                      <UploadImgs
                        v-model="formData.data.accidentPhotos"
                        :limit="4"
                        :fileSize="20"
                        :fileType="['image/jpeg', 'image/png']"
                        height="130px"
                        width="200px"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </ContentWrap>
        <ContentWrap>
          <div class="content">
            <div class="content_head flex-s">
              <div class="line"></div>
              <div class="title">人员配置</div>
            </div>
            <div class="content_main">
              <el-row class="-mb-15px" :gutter="24">
                <el-col :span="24" class="mt-24">
                  <el-form-item label="事故人员：">
                    <div class="mb-12">
                      <el-button
                        v-for="(item, index) in btnList"
                        :key="item.id"
                        :type="item.isCheck ? 'primary' : 'default'"
                        @click="checkBtn(item, index)"
                      >
                        {{ item.name }}
                      </el-button>
                    </div>
                    
                    <div class="table_box" v-if="formData.data.btnIds.includes(1)">
                      <div class="flex-s"> <div class="line"></div> 劳务员工</div>
                      <el-table :data="formData.data.laborList">
                        <template v-for="item in laborColumn" :key="item.prop">
                          <el-table-column
                            :width="item.width"
                            :align="item.align ? item.align : 'center'" 
                            :label="item.label"
                            :prop="item.prop"
                          >
                            <template #default="scope">
                              <div v-if="item.prop == 'status'">
                                <el-tag type="info" v-if="scope.row.status == 0">离职</el-tag>
                                <el-tag type="warning" v-else-if="scope.row.status == 1">留职</el-tag>
                                <el-tag type="success" v-else-if="scope.row.status == 2">在职</el-tag>
                                <span v-else>-</span>
                              </div>
                              <div v-else-if="item.prop == 'skillName'">
                                <div v-if="scope.row.skillName">{{ scope.row.skillName }}</div>
                                <div v-else>-</div>
                              </div>
                              <div v-else>
                                {{ scope.row[item.prop] || '-' }}
                              </div>
                            </template>
                          </el-table-column>
                        </template>
                  
                        <el-table-column :width="100" align="center" label="操作">
                          <template #default="scope">
                            <el-button link type="danger" @click="laborDel(scope.$index)">
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                  
                      </el-table>
                      <el-button class="addRow" @click="addLabor" plain>
                        <el-icon class="mr-6"><Plus /></el-icon>  添加
                      </el-button>
                    </div>
  
                    <div class="table_box" v-if="formData.data.btnIds.includes(2)">
                      <div class="flex-s"> <div class="line"></div> 内部员工</div>
                      <el-table :data="formData.data.internaList">
                        <template v-for="item in personalColumn" :key="item.prop">
                          <el-table-column
                            :width="item.width"
                            :align="item.align ? item.align : 'center'" 
                            :label="item.label"
                            :prop="item.prop"
                          >
                            <template #default="scope">
                              <div v-if="item.prop === 'position'">
                                <span v-if="scope.row.position && scope.row.position.length > 0">{{ scope.row.position.join('/') }}</span>
                                <span v-else>-</span>
                              </div>
                              <div v-else-if="item.prop === 'departmentId'">{{ scope.row.departmentId ? findDeptNameById(deptTree, scope.row.departmentId) : '-' }}</div>
                              <div v-else>{{ scope.row[item.prop] ? scope.row[item.prop] : '-' }}</div>
                            </template>
                          </el-table-column>
                        </template>
                  
                        <el-table-column :width="100" align="center" label="操作">
                          <template #default="scope">
                            <el-button link type="danger" @click="companiesDel(scope.$index)">
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                  
                      </el-table>
                      <el-button class="addRow" @click="addCompanies(2, '内部员工')" plain>
                        <el-icon class="mr-6"><Plus /></el-icon>  添加
                      </el-button>
                    </div>
  
                    <div class="table_box" v-if="formData.data.btnIds.includes(3)">
                      <div class="flex-s"> <div class="line"></div> 其他人员</div>
                      <el-table :data="formData.data.otherList">
                        <el-table-column align="center" label="姓名" prop="userName">
                          <template #default="scope">
                            <el-input 
                              class="formInp"
                              v-if="scope.row.editable" 
                              v-model="scope.row.userName" 
                              clearable 
                              placeholder="请输入姓名"
                            />
                            <div v-else>{{ scope.row.userName }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="性别" prop="gender">
                          <template #default="scope">
                            <el-select 
                              class="formInp"
                              v-if="scope.row.editable" 
                              v-model="scope.row.gender"
                              placeholder="请选择性别"
                            >
                              <el-option label="男" :value="1" />
                              <el-option label="女" :value="0" />
                            </el-select>
                            <div v-else>{{ scope.row.gender === 1 ? '男' : '女' }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="年龄" prop="age">
                          <template #default="scope">
                            <el-input-number  
                              class="formInp"
                              v-if="scope.row.editable" 
                              v-model="scope.row.age" 
                              clearable
                              controls-position="right" 
                              :max="150"
                              placeholder="请输入年龄"
                            />
                            <div v-else>{{ scope.row.age }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="联系电话" prop="phone">
                          <template #default="scope">
                            <el-input
                              class="formInp"
                              v-if="scope.row.editable" 
                              v-model="scope.row.phone" 
                              clearable
                              :maxlength="11"
                              placeholder="请输入联系电话"
                            />
                            <div v-else>{{ scope.row.phone }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="紧急联系人" prop="emergencyContact">
                          <template #default="scope">
                            <el-input
                              class="formInp"
                              v-if="scope.row.editable" 
                              v-model="scope.row.emergencyContact" 
                              clearable
                              placeholder="请输入紧急联系人"
                            />
                            <div v-else>{{ scope.row.emergencyContact }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" label="紧急联系电话" prop="urgentPhone">
                          <template #default="scope">
                            <el-input
                              class="formInp"
                              v-if="scope.row.editable" 
                              v-model="scope.row.urgentPhone" 
                              clearable
                              :maxlength="11"
                              placeholder="请输入联系电话"
                            />
                            <div v-else>{{ scope.row.urgentPhone }}</div>
                          </template>
                        </el-table-column>
                        <el-table-column :width="200" align="center" label="操作">
                          <template #default="scope">
  
                            <div v-if="scope.row.editable">
                              <el-button link type="info" @click="cancle(scope.$index)">取消</el-button>
                              <el-button link type="primary" @click="save(scope.row, scope.$index)">保存</el-button>
                            </div>
                            <div v-else>
                              <el-button link type="primary" @click="edit(scope.$index)">
                                编辑
                              </el-button>
                              <el-popconfirm
                                class="box-item"
                                title="确定删除？"
                                placement="top-end"
                                @confirm="del(scope.$index)"
                              >
                                <template #reference>
                                  <el-button link type="danger">
                                    删除
                                  </el-button>
                                </template>
                              </el-popconfirm>
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                      <el-button @click="addRow" plain class="addRow">
                        <el-icon class="mr-6"><Plus /></el-icon>  添加
                      </el-button>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="应急预案：" class="mt-24">
                    <el-table :data="formData.data.emergencyList">
                      <template v-for="item in emergencyColumn" :key="item.prop">
                        <el-table-column
                          :width="item.width"
                          :align="item.align ? item.align : 'center'" 
                          :label="item.label"
                          :prop="item.prop"
                        >
                          <template #default="scope">
                            <div v-if="item.prop === 'type'">
                              <span>{{ filingTypeList.find(item => item.value == scope.row.type)?.label || '-' }}</span>
                            </div>
                            <div v-else-if="item.prop === 'departmentId'">
                              {{ findDeptNameById(deptTree, scope.row.departmentId) || '-' }}
                            </div>
                            <div v-else-if="item.prop === 'emergencyTime'">{{ scope.row.emergencyTime ? formatDate(scope.row.emergencyTime) : '-' }}</div>
                            <div v-else>
                              {{ scope.row[item.prop] || '-' }}
                            </div>
                          </template>
                        </el-table-column>
                      </template>
                
                      <el-table-column :width="100" align="center" label="操作">
                        <template #default="scope">
                          <el-button link type="danger" @click="emergencyDel(scope.$index)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                
                    </el-table>
                    <el-button class="addRow" @click="addEmergency" plain>
                      <el-icon class="mr-6"><Plus /></el-icon>  添加
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </ContentWrap>
        <ContentWrap class="flex-c">
          <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm(1)">保存</el-button>
          <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm(2)">提交</el-button>
          <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
        </ContentWrap>
      </div>
      <div v-else>
        <ResultForm ref="resultFormRef" @close="goClose"/>
      </div>
    </el-tab-pane>
  </el-tabs>




  <personalDialog ref="personalDialogRef" @change="personalChange"/>

  <laborDialog ref="laborDialogRef" @change="laborChange"/>

  <EmergencyDialog ref="emergencyDialogRef" @change="emergencyChange"/>
</template>
<script setup>
  import {ref,reactive,nextTick} from "vue"
  import { isPhoneNumber } from '@/utils/index'
  import { Plus } from '@element-plus/icons-vue'
  import { 
    formRules, 
    personalColumn, 
    laborColumn, 
    emergencyColumn,
    levelList,
    statusList,
  } from './jsonAndRules'
  import { formatDateToYMD } from '@/utils/index'
  import { defaultProps } from '@/utils/tree'
  import { UploadImgs, UploadFile } from "@/components/UploadFile/index.ts"
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import personalDialog from './personalDialog.vue'
  import laborDialog from './laborDialog.vue'
  import EmergencyDialog from './emergencyDialog.vue'
  import ResultForm from './resultForm.vue'
  import { formatDate } from '@/utils/formatTime'
  const filingTypeList = ref(getIntDictOptions(DICT_TYPE.FILING_TYPE)) 
  provide('filingTypeList', filingTypeList)
  const findDeptNameById = inject('findDeptNameById')
  const goBack = inject('goBack', () => {})
  let pageStatus = ref(1) // 1新增  2编辑
  const deptTree = inject('deptTree')
  const personalDialogRef = ref(null)
  const laborDialogRef = ref(null)
  const emergencyDialogRef = ref(null)
  const message = useMessage() // 消息弹窗
  const loading = ref(false) // 列表的加载中
  const formRef = ref(null)
  const resultFormRef = ref(null)
  const formData = reactive({
    data: {
      id: 1,
      levelId: '', // 事故等级
      address: '', // 事故地点
      departmentId: '', // 责任部门
      accidentTime: '', // 事故时间
      declarePersonId: '', //  申报人Id
      declarePersonName: '', // 申报人姓名
      declarePersonPhone: '', // 申报人手机号
      remark: '', // 事故描述
      accidentPhotos: [], // 事故照片
      attachment: [], // 附件
      btnIds: [1], // 按钮id
      laborList: [], // 劳务员工
      internaList: [], // 内部员工
      otherList: [], // 其他人员
      emergencyList: [], // 应急预案
    }
  })
  const btnList = ref([
    {id: 1, name: '添加劳务员工', isCheck: true},
    {id: 2, name: '按角内部员工', isCheck: false},
    {id: 3, name: '按部其他人员', isCheck: false},
  ])
  let copyData = ref([])

  const init = (type, id) => {
    pageStatus.value = type
  }

  const tabActive = ref(1)
  const tabList = ref([
    {id: 1, name: '事故信息'},
    {id: 2, name: '事故结果'},
  ])
  const tabClick = (tab) => {
    tabActive.value = tab.props.name
    if(tab.props.name === 2){
      nextTick(() => {
        resultFormRef.value[0].init(formData.data.id)
      })
    }
  }
  const goClose = () => {
    // 让事故结果页，返回事故信息
    tabActive.value = 1
  }
  const checkBtn = (item, index) => {
    const {id, isCheck} = item
    let flag = btnList.value.filter(item => item.isCheck).length
    if(isCheck){
      if(flag === 1){
        message.error('至少添加一个劳务人员/内部员工/其他人员')
        return
      }
      btnList.value[index].isCheck = false
    }else{
      btnList.value[index].isCheck = true
    }
    formData.data.btnIds = btnList.value.filter(item => item.isCheck).map(item => item.id)
  }


  /** 选劳务员工逻辑处理 - 开始 */
  const addLabor = () => {
    laborDialogRef.value.init()
  }
  const laborChange = (data) => {
    console.log(data, 'laborChange');
    if(formData.data.laborList.length > 0) {
      let newData = formData.data.laborList.concat(data)
      // 使用 reduce 去重
      newData = newData.reduce((acc, cur) => {
        if (!acc.some(item => item.id === cur.id)) {
          acc.push(cur)
        }
        return acc
      }, [])
      formData.data.laborList = newData
    }else{
      formData.data.laborList = data
    }
  }
  const laborDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.laborList.splice(index, 1)
    } catch {}
  }
  /** 选劳务员工逻辑处理 - 结束 */


  /** 选内部员工逻辑处理 - 开始 */
  const addCompanies = (type, titleType) => {
    personalDialogRef.value.init(type, titleType)
  }
  const personalChange = (data, type) => {
    console.log(data, type, 'personalChange');
    
    if(type === 1){
      const { id, name, phone, position, departmentId } = data
      formData.data.declarePersonId = id
      formData.data.declarePersonName = name
      formData.data.declarePersonPhone = phone
    }else{
      if(formData.data.internaList.length > 0) {
        let newData = formData.data.internaList.concat(data)
        // 使用 reduce 去重
        newData = newData.reduce((acc, cur) => {
          if (!acc.some(item => item.id === cur.id)) {
            acc.push(cur)
          }
          return acc
        }, [])
        formData.data.internaList = newData
      }else{
        formData.data.internaList = data
      }
    }

  }
  const companiesDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.internaList.splice(index, 1)
    } catch {}
  } 
  /** 选内部员工逻辑处理 - 结束 */


  /** 选其他人员逻辑处理 - 开始 */
  const addRow = () => {
    let otherList = JSON.parse(JSON.stringify(formData.data.otherList))
    copyData.value = JSON.parse(JSON.stringify(otherList))
    let flag = otherList.find(item => item.editable)
    if (flag) {
      ElMessage.warning('请先保存当前数据')
      return
    }
    otherList.push({
      userName: null, 
      gender: null, 
      age: null, 
      phone: null, 
      emergencyContact: null, 
      urgentPhone: null,
      editable: true,
    })
    formData.data.otherList = otherList
  }
  const edit = (index) => {
    let otherList = JSON.parse(JSON.stringify(formData.data.otherList))
    let flag = otherList.find(item => item.editable)
    if (flag) {
      ElMessage.warning('请先保存当前数据')
      return
    }
    copyData.value = JSON.parse(JSON.stringify(otherList))
    otherList[index].editable = true
    formData.data.otherList = otherList
  }
  const del = (index) => {
    let otherList = JSON.parse(JSON.stringify(formData.data.otherList))
    otherList.splice(index, 1)
    formData.data.otherList = otherList
  }
  const cancle = () => {
    let otherList = JSON.parse(JSON.stringify(copyData.value))
    formData.data.otherList = otherList
  }
  const save = (row, index) => {
    let otherList = JSON.parse(JSON.stringify(formData.data.otherList))

    const {userName, gender, age, phone, emergencyContact, urgentPhone} = row
    if (!userName) {
      message.warning('请输入姓名')
      return
    }
    if (!gender) {
      message.warning('请选择性别')
      return
    }
    if (!age) {
      message.warning('请输入年龄')
      return
    }
    if (!phone) {
      message.warning('请输入联系电话')
      return
    }
    if (!isPhoneNumber(phone)) {
      message.warning('请输入正确的联系电话')
      return
    }
    if (!emergencyContact) {
      message.warning('请输入紧急联系人')
      return
    }
    if (!urgentPhone) {
      message.warning('请输入紧急联系人电话')
      return
    }
    if (!isPhoneNumber(urgentPhone)) {
      message.warning('请输入正确的紧急联系人电话')
      return
    }
    otherList.forEach(item => item.editable = false)
    formData.data.otherList = otherList
  }
  /** 选其他人员逻辑处理 - 结束 */


  /** 选应急预案逻辑处理 - 开始 */
  const addEmergency = () => {
    emergencyDialogRef.value.init()
  }
  const emergencyChange = (data) => {
    console.log(data, 'emergencyChange');
    if(formData.data.emergencyList.length > 0) {
      let newData = formData.data.emergencyList.concat(data)
      // 使用 reduce 去重
      newData = newData.reduce((acc, cur) => {
        if (!acc.some(item => item.id === cur.id)) {
          acc.push(cur)
        }
        return acc
      }, [])
      formData.data.emergencyList = newData
    }else{
      formData.data.emergencyList = data
    }
  }
  const emergencyDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      formData.data.emergencyList.splice(index, 1)
    } catch {}
  } 
  /** 选应急预案逻辑处理 - 结束 */

  const closeForm = () => {
    // 关闭表单弹窗逻辑
    goBack()
  }
  const submitForm = (type) => {
    const formEl = formRef.value[0]
    console.log(formEl, 'formEl');
    if (!formEl) return
    formEl.validate((valid, fields) => {
      if (valid) {

        console.log(formData.data, valid, '走这里来了？？？');
      }else{
        for(let key in fields){
          message.error(fields[key][0].message)
        }
      }
    })
  }
  defineExpose({ init })
</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    margin-bottom: 24px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
    .content_main {
        width: 100%;
        padding: 0 32px;
        box-sizing: border-box;
    }
}
::v-deep .el-form-item{
  width: 100%;
}
.coord{
  height: 32px;
  box-sizing: border-box;
  padding: 4px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  color: #636660;
  &:hover{
    border-color: #bcbdc0;
  }
}
.table_box{
  margin-top: 24px;
  width: 100%;
  .line{
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #50B5FF;
    margin-right: 4px;
  }
}
.cursor_pointer{
  &:hover{
    border-color: rgb(64, 158, 255);
  }
}
.formInp{
  width: 100%;
}
.addRow{
  margin-top: 12px;
  width: 100%;
}
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .el-upload-list.el-upload-list--text{
  overflow-y: scroll;
  height: 100px;
  margin: 0 !important;
}
</style>
